package com.xingdata.jjxc.activity;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.services.core.PoiItem;
import com.amap.api.services.core.SuggestionCity;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.amap.api.services.poisearch.PoiSearch.OnPoiSearchListener;
import com.xingdata.jjxc.ComEntity;
import com.xingdata.jjxc.Common;
import com.xingdata.jjxc.R;
import com.xingdata.jjxc.RequestCode;
import com.xingdata.jjxc.adapter.PoiListViewAdapter;
import com.xingdata.jjxc.base.BaseActivity;
import com.xingdata.jjxc.enty.NaviHistoryEntity;
import com.xingdata.jjxc.favorites.FavoritesActivity;
import com.xingdata.jjxc.favorites.FavoritesEntity;
import com.xingdata.jjxc.record.MyCustomListView;
import com.xingdata.jjxc.record.RecordSQLiteOpenHelper;
import com.xingdata.jjxc.record.SearchRecordAdapter;
import com.xingdata.jjxc.utils.JUtils;
import com.xingdata.jjxc.utils.Log;
import com.xingdata.jjxc.utils.SystemInfo;

public class HomeCompanySetActivity extends BaseActivity implements OnClickListener, OnPoiSearchListener {
	final static String TAG = "HomeCompanySetActivity";
	
	/** 编辑框edittext */
	private EditText serchEditText;
	/** 搜索button*/
	
	private ImageView search_btn;
	/** 高德poi兴趣点-搜索listview */
	private ListView poiSearchListView;
	/** 高德poi兴趣点-adapter*/
	private PoiListViewAdapter poiListViewAdapter;
	/** 高德poi兴趣点-数据*/
	private ArrayList<NaviHistoryEntity> naviHistoryEntityList = new ArrayList<NaviHistoryEntity>();
	
	private PoiSearch.Query query;// Poi查询条件类
	private PoiSearch poiSearch;// POI搜索
	private PoiResult poiResult;//poi返回的结果
	
	/** 需要进行隐藏的界面 */
	private LinearLayout ll;
	
	/** 历史搜索记录listview列表 */
	private ListView searchRecord_listview;
	/** adapter */
	private SearchRecordAdapter searchRecordAdapter;
	
	private ImageView goBack;
	/** 收藏地点 */
	private LinearLayout hc_collect_site;
	/** 地图选点 */
	private LinearLayout hc_map_select;
	/** 历史搜索记录listview列表 */
	private MyCustomListView search_record_listview;
	private RecordSQLiteOpenHelper helper = new RecordSQLiteOpenHelper(this);
	private BaseAdapter adapter;
	private SQLiteDatabase db;
	/** 清除按钮 */
	private Button btn_clear_record;
	
	@Override
	protected int getContentViewId() {
		// TODO Auto-generated method stub
		return R.layout.navi_homecompany_setting;
	}

	@Override
	protected String getTitleText() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	protected void initViews() {
		// 修改字体
		Typeface font = Typeface.createFromAsset(getAssets(), JUtils.TypefacePath);
		
		/*搜索历史列表*/
		search_record_listview = (MyCustomListView) findViewById(R.id.search_record_listview);
		search_record_listview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				TextView textView = (TextView) view.findViewById(R.id.search_placeName);
				String name = textView.getText().toString();
				serchEditText.setText(name);
				search_btn.performClick();//模拟点击事件
				Toast.makeText(HomeCompanySetActivity.this, name, Toast.LENGTH_SHORT).show();
			}
		});
		
		/*清除记录按钮*/
		btn_clear_record = (Button) findViewById(R.id.btn_clear_record); 
		btn_clear_record.setTypeface(font);
		btn_clear_record.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				deleteData();
				queryData("");
			}
		});
		
		
		queryData("");
		
		//需要隐藏的界面
		ll = (LinearLayout) findViewById(R.id.ll);
		//返回
		goBack = (ImageView) findViewById(R.id.goBack);
		goBack.setOnClickListener(this);
		//搜索结果listview
		poiSearchListView = (ListView) findViewById(R.id.poiSearchListView);
		poiListViewAdapter = new PoiListViewAdapter(naviHistoryEntityList, this);
		poiSearchListView.setAdapter(poiListViewAdapter);
		poiSearchListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
				// TODO Auto-generated method stub
				NaviHistoryEntity naviHistoryEntity = naviHistoryEntityList.get(position);
				Log.d(TAG, "position="+naviHistoryEntity.getloca_address());
				Intent intent = new Intent();
				Bundle bundle = new Bundle();
				
				bundle.putSerializable("homeOrcompany", naviHistoryEntity);
				
				intent.putExtras(bundle);
				
				setResult(RESULT_OK, intent);
				finish();
			}
		});
		
		//搜索按钮
		search_btn = (ImageView) findViewById(R.id.search_btn);
		search_btn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				String strSerach = serchEditText.getText().toString().trim();
				if (strSerach.length() == 0) {
					showToast("搜索框内容不能为空！");
					return;
				}
				doSearchQuery(strSerach);
				ll.setVisibility(View.GONE);
				poiSearchListView.setVisibility(View.VISIBLE);
				
				// 先判断搜索字符串是否已经保存，字符串不为空，然后就保存为历史搜索记录
				boolean hasData = hasData(serchEditText.getText().toString().trim());
				if (!hasData && !TextUtils.isEmpty(strSerach)) {
					insertData(serchEditText.getText().toString().trim());
					queryData("");
				}
			}
		});
		//搜索框
		serchEditText = (EditText) findViewById(R.id.com_search_map_et);
		serchEditText.setOnKeyListener(new OnKeyListener() {
			
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {// 修改回车键功能
					search_btn.performClick();//模拟一次search_btn的点击事件
					// 先隐藏键盘
					((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(
							getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
					String str = serchEditText.getText().toString().trim();
					// 按完搜索键后将当前查询的关键字保存起来,如果该关键字已经存在就不执行保存
					boolean hasData = hasData(serchEditText.getText().toString().trim());
					if (!hasData && !TextUtils.isEmpty(str)) {
						insertData(serchEditText.getText().toString().trim());
						queryData("");
					}
				}
				return false;
			}
		});
		//收藏地点
		hc_collect_site = (LinearLayout) findViewById(R.id.hc_collect_site);
		hc_collect_site.setOnClickListener(this);
		//地图选点
		hc_map_select = (LinearLayout) findViewById(R.id.hc_map_select);
		hc_map_select.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.goBack:
			finish();
			break;
			//收藏地点
		case R.id.hc_collect_site:

			Intent intent_collect_site =new Intent(HomeCompanySetActivity.this, FavoritesActivity.class);
			startActivityForResult(intent_collect_site, RequestCode.REQUESTCODE_FINISH);
			
			break;
			//地图选点
		case R.id.hc_map_select:
			
			Intent intent_map_select = new Intent(HomeCompanySetActivity.this,MapSelectActivity.class);
			startActivityForResult(intent_map_select, RequestCode.REQUESTCODE_FINISH);
			
			break;

		default:
			break;
		}
	}
	
	/** 目的从NaviSerchActivity(A)跳转到HomeCompanySetActivity(B)跳转到MapSelectActivity(C)，
	 * 然后从C到A的时候，直接用一个返回监听，HomeCompanySetActivity(B)自己结束了自己
	 * 并且C将数据传给B，然后由B把数据传给了A */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		// 请求从地图选点界面返回结果
		case RequestCode.REQUESTCODE_FINISH:
			if (resultCode==RESULT_OK) {
				
				Intent intent = new Intent();
				Bundle bundle = new Bundle();
				
				ComEntity comEntity = (ComEntity) data.getSerializableExtra(Common.MAPSELECT_PLACENAME);
				bundle.putSerializable(Common.MAPSELECT_PLACENAME_FROMEHOMECOMPANYACT, comEntity);
				

				/*获取收藏夹传来数据，设置家或者公司地址*/
				FavoritesEntity favoritesEntity = (FavoritesEntity) data.getSerializableExtra(Common.PLACE_NAME_INFAVORITES);
				if (favoritesEntity != null) {
					bundle.putSerializable(Common.PLACE_NAME_MIDDLE, favoritesEntity);
					intent.putExtras(bundle);
				}
				
				intent.putExtras(bundle);
				setResult(RESULT_OK, intent);
				finish();
			}
			break;

		default:
			break;
		}
		
	}
	
	/**
	 * 插入数据
	 */
	private void insertData(String tempName) {
		db = helper.getWritableDatabase();
		db.execSQL("insert into records(name) values('" + tempName + "')");
		db.close();
	}
	
	/**
	 * 模糊查询数据
	 */
	private void queryData(String tempName) {
		Cursor cursor = helper.getReadableDatabase().rawQuery(
				"select id as _id,name from records where name like '%" + tempName + "%' order by id desc ", null);
		// 创建adapter适配器对象
		adapter = new SimpleCursorAdapter(this, R.layout.search_record_item, cursor, new String[] { "name" },
				new int[] { R.id.search_placeName }, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
		// 设置适配器
		search_record_listview.setAdapter(adapter);
		adapter.notifyDataSetChanged();
	}
	
	/**
	 * 检查数据库中是否已经有该条记录
	 */
	private boolean hasData(String tempName) {
		Cursor cursor = helper.getReadableDatabase().rawQuery(
				"select id as _id,name from records where name =?", new String[]{tempName});
		//判断是否有下一个
		return cursor.moveToNext();
	}
	
	/**
	 * 清空数据
	 */
	private void deleteData() {
		db = helper.getWritableDatabase();
		db.execSQL("delete from records");
		db.close();
	}
	
	/**
	 * 开始进行poi搜索
	 */
	protected void doSearchQuery(String reslut) {
		int currentPage = 0;
		query = new PoiSearch.Query(reslut, "", SystemInfo.City);// 第一个参数表示搜索字符串，第二个参数表示poi搜索类型，第三个参数表示poi搜索区域（空字符串代表全国）
		query.setPageSize(10);// 设置每页最多返回多少条poiitem，在listview最多显示10条相关搜索结果信息
		query.setPageNum(currentPage);// 设置查第一页
		
		poiSearch = new PoiSearch(this, query);
		poiSearch.setOnPoiSearchListener(this);
		poiSearch.searchPOIAsyn();
		
	}

	@Override
	public void onPoiSearched(PoiResult result, int rCode) {
		// TODO Auto-generated method stub
		if (rCode == 0) {
			if (result != null && result.getQuery() != null) {// 搜索poi的结果
				if (result.getQuery().equals(query)) {// 是否是同一条
					poiResult = result;
					// 取得搜索到的poiitems有多少页
					List<PoiItem> poiItems = poiResult.getPois();// 取得第一页的poiitem数据，页数从数字0开始
					List<SuggestionCity> suggestionCities = poiResult.getSearchSuggestionCitys();// 当搜索不到poiitem数据时，会返回含有搜索关键字的城市信息
					
					if (poiItems != null && poiItems.size() > 0) {
						
						naviHistoryEntityList.clear();
						
						PoiItem poiItem = null;
						
						NaviHistoryEntity naviHistoryEntity = null;
						
						for (int i = 0; i < poiItems.size(); i++) {
							
							poiItem = poiItems.get(i);
							
							naviHistoryEntity = new NaviHistoryEntity();
							naviHistoryEntity.setloca_id(UUID.randomUUID().toString());
							naviHistoryEntity.setloca_nickname(poiItem.getTitle());
							naviHistoryEntity.setloca_address(poiItem.getSnippet());
							naviHistoryEntity.setloca_lng(poiItem.getLatLonPoint().getLongitude() + "");
							naviHistoryEntity.setloca_lat(poiItem.getLatLonPoint().getLatitude() + "");
							naviHistoryEntity.setloca_areaid(poiItem.getProvinceCode());
							
							naviHistoryEntityList.add(naviHistoryEntity);
							poiListViewAdapter.notifyDataSetChanged();
						}
					} else if (suggestionCities != null && suggestionCities.size() > 0) {
						showToast("这里没有搜索到结果推荐...");
					} else {
						showToast(getResources().getString(R.string.no_result).toString());
					}
				}
			} else {
				showToast(getResources().getString(R.string.no_result).toString());
			}
		} else if (rCode == 27) {
			showToast(getResources().getString(R.string.error_network).toString());
		} else if (rCode == 32) {
			showToast(getResources().getString(R.string.error_key).toString());
		} else {
			showToast(getResources().getString(R.string.error_other).toString());
		}
	}

}
